#!/usr/env/bin python
# -*- coding: utf-8 -*-

# @Time    : 2020-10-09 11:53 上午
# @Author  : yangdy
# @File    : 2020-10-04.2.两数相加[补]
# @Software: PyCharmCE
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        head, p = None, None
        p1, p2 = l1, l2
        e = 0
        while p1 or p2:
            a = (p1.val if p1 else 0) + (p2.val if p2 else 0) + e
            e = a // 10
            np = ListNode(a % 10)
            if not head:
                head, p = np, np
            else:
                p.next = np
                p = np
            p1 = p1.next if p1 else None
            p2 = p2.next if p2 else None
        while e > 0:
            p.next = ListNode(e % 10)
            e = e // 10
            p = p.next
        return head
